﻿using RpcCentral.Collect.Model;
using RpcCentral.Common;
using RpcCentral.DAL;
using RpcCentral.Model;
using RpcHelper;

namespace RpcCentral.Collect.Controller
{
    public class RpcServerConfigController : DataSyncClass
    {
        public RpcServerConfigController(long rpcMerId, long sysTypeId)
        {
            RpcMerId = rpcMerId;
            SystemTypeId = sysTypeId;
        }
        private IRpcMerConfigDAL _RpcMerConfig
        {
            get => UnityHelper.Resolve<IRpcMerConfigDAL>();
        }
        private IRemoteServerDAL _RemoteServer
        {
            get => UnityHelper.Resolve<IRemoteServerDAL>();
        }
        private IRemoteServerGroupDAL _RemoteServerGroup
        {
            get => UnityHelper.Resolve<IRemoteServerGroupDAL>();
        }
        public long RpcMerId
        {
            get;
        }

        public long SystemTypeId
        {
            get;
        }
        public RpcServiceConfig[] Server { get; private set; }
        /// <summary>
        /// 是否启用区域隔离
        /// </summary>
        public bool IsRegionIsolate { get; private set; }
        /// <summary>
        /// 隔离级别
        /// </summary>
        public bool IsolateLevel { get; private set; }
        public int Ver { get => _Ver;  }

        private int _Ver = 0;
        protected override void SyncData()
        {
            RemoteConfig[] list = this._RemoteServerGroup.GetRemoteServer(RpcMerId, SystemTypeId);
            if (!list.IsNull())
            {
                BasicServer[] servers = _RemoteServer.GetRemoteServerConfig(list.ConvertAll(a => a.ServerId));
                Server = servers.ConvertAll(a =>
                {
                    return new RpcServiceConfig
                    {
                        RegionId = a.RegionId,
                        ServerId = a.Id,
                        Weight = list.Find(b => b.ServerId == a.Id, b => b.Weight, a.Weight),
                        VerNum = a.VerNum
                    };
                });
            }
            else
            {
                Server = new RpcServiceConfig[0];
            }
            MerConfig config = this._RpcMerConfig.GetConfig(RpcMerId, SystemTypeId);
            if (config == null)
            {
                this.IsolateLevel = false;
                this.IsRegionIsolate = true;
            }
            else
            {
                this.IsolateLevel = config.IsolateLevel;
                this.IsRegionIsolate = config.IsRegionIsolate;
            }
            this._Ver = Tools.GetRandom();
        }
        private bool _CheckVer(ref int ver)
        {
            if (ver != _Ver)
            {
                ver = _Ver;
                return true;
            }
            return false;
        }
    }
}
